const app = getApp();
var config = require('../../config.js');
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginName : '', // 账号
    password : '',  // 密码
    sources : '22', //支付方式{1支付宝, 2微信, 11支付宝APP, 12微信APP, 21支付宝小程序, 22微信小程序, 24招行一网通}
    consumeTypeCode : '', //消费项目
    insuranceCodeId : '', //保险险种， 消费项目不是保险 不必填
    loginSn : '', //登陆串号
    appServiceType : '', //业务类型1(物流算盘) 2:新app用户购买
    appServicePriceId : '', //服务时间价格表ID
    money : '0', // 金额
    type : '', //支付类型 0 正常支付 1 二次支付
    onLinePayResult : '', //支付结果串
    payResult : '', //支付结果
    payParam : '', //支付结果参数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      openid : wx.getStorageSync('openid'),
      appid : config.appid,
      loginName : options.loginName,
      password : options.password,
      consumeTypeCode : options.consumeTypeCode,
      insuranceCodeId : options.insuranceCodeId,
      loginSn : options.loginSn,
      appServiceType : options.appServiceType,
      appServicePriceId : options.appServicePriceId,
      money : options.money,
      type : options.type,
      onLinePayResult : options.onLinePayResult
    })
    console.log(this.data.type);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    if(that.data.openid === '' || that.data.openid === null){
      that.getLogin();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  toPay: function () {
    var that = this;
    that.generateOrder();
  },

  //获取微信openid
  getLogin(){
    var _this = this;
    //微信登录
    wx.login({
      success: res => {
        if (res.code) {
          _this.getOpenId(res.code);
        }
      }
    })
  },

  getOpenId: function (code) {
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    wx.hideTabBar();
    var _this = this
    wx.request({
      url: config.openIdUrl,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        "code": code,
        "tenantCode": "",
        "latitude": "",
        "longitude": ""
      },
      success: function (result) {
        var data = result.data;
        console.info(data);
        if (data.success) {
          if (data.openid) {
            _this.setData({
              openid : data.openid
            })
            wx.hideLoading();
          }
        } else {
          _this.tip(data.msg, 'none')
        }
      },
      fail: function ({ errMsg }) {
        console.log(errMsg)
      },
      complete: function () {
        wx.hideLoading();
      }
    })
    
  },

  /**生成商户订单 */
  generateOrder: function () {
    var that = this;
    console.log("openid" + that.data.openid)
    wx.showLoading({
      title: '请求支付中...',
    })
    if(that.data.payParam !== ''){
      that.pay(that.data.payParam);
    }else{
      //统一支付 
      return new Promise((resolve, reject) => {
        wx.request({
          url: config.requestUrl + "miniPay/toPay",
          method: 'GET',
          data: {
            openid: that.data.openid,
            // appid : app.appid,
            appid : that.data.appid,
            loginName : that.data.loginName,
            password : that.data.password,
            sources : that.data.sources,
            consumeTypeCode : that.data.consumeTypeCode,
            insuranceCodeId : that.data.insuranceCodeId,
            loginSn : that.data.loginSn,
            appServiceType : that.data.appServiceType,
            appServicePriceId : that.data.appServicePriceId,
            money : that.data.money
          },
          success: res => {
            wx.hideLoading(); 
            resolve(res)
            console.log(res);
            if(res.data.success){
              //发起支付 
              var timeStamp = res.data.object.timeStamp;
              var packages = res.data.object.package;
              var paySign = res.data.object.paySign;
              var nonceStr = res.data.object.nonceStr;
              var signType =  res.data.object.signType;
              var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": signType, "nonceStr": nonceStr };
              that.setData({
                payParam : param
              })
              that.pay(param);
            }else{
              wx.showToast({
                title: res.data.message,
                icon : 'none'
              })
            }
          },
          fail: res => {
            reject(res)
          }
        })
      })  
    }
  },

  /**
   * 二次支付
   */
  payAgain(){
    var that = this;
    var result = JSON.parse(that.data.onLinePayResult);
    console.log(result.responseBody);
    var onLinePayResult = JSON.parse(result.responseBody);
    var timeStamp = onLinePayResult.timeStamp;
    var packages = onLinePayResult.package;
    var paySign = onLinePayResult.paySign;
    var nonceStr = onLinePayResult.nonceStr;
    var signType =  onLinePayResult.signType;
    var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": signType, "nonceStr": nonceStr };
    that.pay(param);
  },

  pay(param){
    var that = this;
    console.log('发起支付');
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: param.signType,
      paySign: param.paySign,
      success: function (event) {
        // success
        console.log(event);
        that.setData({
          payResult : 'success'
        })
        setTimeout(function(){
          wx.reLaunch({
            url: './wechatPaymentSuc?consumeTypeCode=' + that.data.consumeTypeCode +
              '&money=' + that.data.money + '&payResult=' + that.data.payResult,
          })
        },200)
      },
      fail: function (error) {
        // fail
        that.setData({
          payResult : 'fail'
        })
        wx.showToast({
          title: '支付失败，请联系管理员',
          icon : 'none'
        })
        console.log("支付失败，失败原因：" + error)
      },
      complete: function () {
        // complete
        console.log("pay complete")
      }
    });
  },

})